<template>
  <div class="search">
    <!-- 搜索栏 -->
    <form action="/">
      <van-search
        v-model="searchValue"
        show-action
        placeholder="请输入搜索关键词"
        shape="round"
        background="#3997f6"
        @search="onSearch(searchValue)"
        @cancel="$router.back()"
        @focus="resultsShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <SearchResults v-if="resultsShow" :searchValue="searchValue" />

    <!-- 联想建议 -->
    <SearchAdvice
      v-else-if="searchValue"
      :searchValue="searchValue"
      @search="onSearch"
    />

    <!-- 历史记录 -->
    <SearchHistory
      v-else
      :searchHistory="searchHistory"
      @search="onSearch"
      @delHistoryAll="searchHistory = $event"
    />
  </div>
</template>
<script>
import SearchAdvice from './components/search-advice'
import SearchHistory from './components/search-history'
import SearchResults from './components/search-results'
import { getStorage, setStorage } from '@/utils/storage'
import { getSearchHistory } from '@/api/search'
import { mapState } from 'vuex'
export default {
  name: 'search',
  data () {
    return {
      searchValue: '',
      resultsShow: false,
      searchHistory: []
    }
  },
  created () {
    this.userSearchHistory()
  },
  methods: {
    onSearch (value) {
      this.searchValue = value
      // 添加搜索记录
      const index = this.searchHistory.indexOf(value)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      this.searchHistory.unshift(value)
      // 已登录
      // 已登录会在搜索结果中自动添加
      // 未登录
      // 这里应该拿取本地数据
      // 判断是否已存在其搜索
      // 存在 如上删除再添加
      // 不存在 直接添加 然后重新设置这个本地数据
      // setStorage('search-history', this.searchHistory)
      // 显示搜索结果组件
      this.resultsShow = true
    },
    async userSearchHistory () {
      if (this.token) {
        // 已登录
        const { data } = await getSearchHistory()
        this.searchHistory = data.data || []
      } else {
        this.searchHistory = getStorage('search-history') || []
      }
    }
  },
  components: {
    SearchAdvice,
    SearchHistory,
    SearchResults
  },
  props: {},
  watch: {
    searchHistory () {
      setStorage('search-history', this.searchHistory)
    }
  },
  computed: {
    ...mapState({
      token: 'token'
    })
  },
  mounted () {}
}
</script>

<style lang="less" scoped></style>
